package cn.zebra.dev.mall.module.discounts.controller;

import cn.zebra.dev.common.restful.Result;
import cn.zebra.dev.ibatis.plus.utils.PageUtils;
import cn.zebra.dev.mall.module.discounts.dto.DiscountsMemberListDTO;
import cn.zebra.dev.member.module.login.service.SecurityMemberService;
import cn.zebra.dev.other.module.discountsMember.entity.DiscountsMemberEntity;
import cn.zebra.dev.other.module.discountsMember.service.DiscountsMemberService;
import cn.zebra.dev.other.module.discountsShop.entity.DiscountsShopEntity;
import cn.zebra.dev.other.module.discountsShop.service.DiscountsShopService;
import cn.zebra.dev.product.module.product.entity.ProductEntity;
import cn.zebra.dev.product.module.product.service.ProductService;
import cn.zebra.dev.shop.module.shop.entity.ShopEntity;
import cn.zebra.dev.shop.module.shop.service.ShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(tags = "用户优惠券模块")
@RequestMapping("/discountMember")
public class DiscountsMemberController {

    @Autowired
    private DiscountsMemberService discountsMemberService;

    @Autowired
    private DiscountsShopService discountsShopService;

    @Autowired
    private ProductService productService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private SecurityMemberService securityMemberService;

    @GetMapping("/list")
    @ApiOperation("用户优惠券列表")
    public Result<PageUtils<DiscountsMemberListDTO>> list(
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page){
        Map<String, Object> map = new HashMap<>();
        map.put("limit", limit);
        map.put("page", page);
        map.put("discountsUserId",securityMemberService.getMemberId());
        PageUtils<DiscountsMemberEntity> pageUtils = discountsMemberService.findPage(map);
        PageUtils<DiscountsMemberListDTO> data = new PageUtils<>(pageUtils);
        List<DiscountsMemberEntity> list = pageUtils.getList();
        List<DiscountsMemberListDTO> dtoList = new LinkedList<>();
        if(list.size() > 0){
            List<Long> discountsIds = list.stream().map(DiscountsMemberEntity::getDiscountsId).collect(Collectors.toList());
            List<DiscountsShopEntity> discountsShopEntities = discountsShopService.findByIds(discountsIds);
            List<Long> shopIds = discountsShopEntities.stream().map(DiscountsShopEntity::getShopId).collect(Collectors.toList());
            List<ShopEntity> shopEntities = shopService.findByIds(shopIds);
            List<Long> productIds = discountsShopEntities.stream().map(DiscountsShopEntity::getProductId).collect(Collectors.toList());
            List<ProductEntity> productEntities = productService.findByIds(productIds);
            list.forEach(entity -> {
                DiscountsMemberListDTO dto = new DiscountsMemberListDTO();
                BeanUtils.copyProperties(entity,dto);
                Optional<DiscountsShopEntity> discountsShopEntityOptional = discountsShopEntities.stream().
                        filter(discountsShopEntity -> discountsShopEntity.getId().equals(entity.getDiscountsId())).findAny();
                if (discountsShopEntityOptional.isPresent()){
                    DiscountsShopEntity discountsShopEntity = discountsShopEntityOptional.get();
                    dto.setDiscountsStatus(discountsShopEntity.getDiscountsStatus());
                    // 如果是商铺类型的优惠券,那么
                    if (entity.getDiscountsType() == 1){
                        Optional<ShopEntity> shopEntityOptional = shopEntities.stream().
                                filter(shopEntity -> shopEntity.getId().equals(discountsShopEntity.getShopId())).findAny();
                        if (shopEntityOptional.isPresent()){
                            ShopEntity shopEntity = shopEntityOptional.get();
                            dto.setShopId(shopEntity.getId());
                            dto.setShopName(shopEntity.getShopName());
                            dto.setShopImage(shopEntity.getShopImage());
                            //如果商品id存在，那么
                            if (discountsShopEntity.getProductId() != 0){
                                Optional<ProductEntity> productEntityOptional= productEntities.stream().
                                        filter(productEntity -> productEntity.getId().equals(discountsShopEntity.getProductId())).findAny();
                                if (productEntityOptional.isPresent()){
                                    ProductEntity productEntity = productEntityOptional.get();
                                    dto.setProductId(productEntity.getId());
                                    dto.setProductImage(productEntity.getProductImage());
                                }
                            }
                        }
                    }
                }
                dtoList.add(dto);
            });
        }
        data.setList(dtoList);
        return Result.success(data);

    }

    @PostMapping("/save/{discountsId}")
    @ApiOperation("领取优惠券")
    @Transactional(rollbackFor = Exception.class)
    public Result save(@PathVariable Long discountsId){
        DiscountsShopEntity discountsEntity = discountsShopService.findById(discountsId);
        if (discountsEntity.getDiscountsStatus() == 2){
            return Result.error("该优惠券已过期，领取失败,请选择其他优惠");
        }
        if (LocalDateTime.now().compareTo(discountsEntity.getEndTime()) > 0 ){
            return Result.error("该优惠券已过期，领取失败,请选择其他优惠");
        }
        DiscountsMemberEntity discountsMemberEntity = new DiscountsMemberEntity();
        discountsMemberEntity.setDiscountsId(discountsEntity.getId());
        discountsMemberEntity.setDiscountsSn(String.valueOf(System.currentTimeMillis()));
        discountsMemberEntity.setDiscountsUserId(securityMemberService.getMemberId());
        discountsMemberEntity.setDiscountsUserd(0); // 设置为未使用
        discountsMemberEntity.setDiscountsType(discountsEntity.getDiscountsType());
        discountsMemberEntity.setCreateTime(LocalDateTime.now());
        discountsMemberEntity.setDeteleFlag(false);
        if (!discountsMemberService.save(discountsMemberEntity)){
            return Result.error("领取失败");
        }
        return Result.success("领取成功");

    }

    @PostMapping("/update/{id}")
    @ApiOperation("使用优惠券")
    public Result update(@PathVariable Long id){
        DiscountsMemberEntity discountsMemberEntity = discountsMemberService.findById(id);
        discountsMemberEntity.setDiscountsUserd(1);
        if (!discountsMemberService.updateDiscountsById(id,discountsMemberEntity)){
            return Result.error("使用优惠券失败");
        }
        return Result.success("使用优惠券成功");
    }

    @GetMapping("/delete/{id}")
    @ApiOperation("店铺删除优惠券")
    public Result delete(@PathVariable Long id) {
        DiscountsMemberEntity entity = discountsMemberService.findById(id);
        entity.setDeteleFlag(true);
        if (!discountsMemberService.updateDiscountsById(id,entity)){
            return Result.success("删除失败");
        }
        return Result.error("删除成功");
    }

}
